#ifndef CROP_CPP
	#include "crop.cpp"
#endif
#include <stdio.h>
#include <string.h>
#include "fileparser.cpp"

using namespace std;

template <class T,class U>
int start(int argc, char *argv[]) {
	int p = 1, rank = 0;
	/*MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &p);*/
	long total = 90002288;
	//fprintf(stderr,"Starting at \n");
	string DIR = "../../data/";
	if (rank == 0) {
		for (int i = 0; i< argc; i++)
			cerr << argv[i]<< endl;
	}

	string FILENAME = argv[1];

	FILENAME = DIR + FILENAME;
	const char * FILEPATH = FILENAME.c_str();
	int k = atoi(argv[2]);
	long int * resvbuf;

	clock_t start = clock();
	long int dist = 0.0;
	for (int j = 0; j < 3; j++) {
		Crop<T> *crop = new Crop<T>(rank, p,
				k);
		MMapFILEParser<U> *fp = new MMapFILEParser<U>((char*) FILEPATH); // Change to command arg
		//fprintf(stderr,"Init done\n");

		while (fp->getinput()) {
			/*		for (int i = 0; i < fp.count; i++) {
			 fprintf(stderr,"(%d,%.4f)", fp.CURR_PTR[i], fp.NUM_PTR[i]);
			 }*/
			crop->crop((int*) fp->CURR_PTR, fp->NUM_PTR, fp->count);
		}
		//fprintf(stderr,"dist at %d: %d\n", rank, crop->pdist[rank]);

		/*Entry *entries = (Entry*) malloc(k * sizeof(Entry));
		 crop->get_summary(entries);
		 free(entries);*/
		//printf ("summarysize: %d\n", crop->summarysize());
		dist += crop->pdist[rank];
		//fprintf(stderr, "dist at %d\t%ld\n", rank, dist);
		/*Entry * entries = (Entry*) malloc(k * sizeof(Entry));
		cerr << crop->to_string() << endl;
		crop->get_summary(entries);*/

		delete crop;
		delete fp;
		//printf ("summarysize: %d\n", crop->summarysize());
	}
	//8676224
	//11250286

	clock_t ends = clock();
	if (rank == 0) {
		resvbuf = (long int*) malloc(sizeof(long int) * p);
	}

	dist = dist;

	//MPI_Gather(&dist, 1, MPI_LONG, resvbuf, 1, MPI_LONG, 0, MPI_COMM_WORLD);

	/*if (rank == 0) {
		cerr << p << "\t" << (double) ((ends - start) / (CLOCKS_PER_SEC * 3.0))
				<< endl;
		double t = (double) ((ends - start) / (CLOCKS_PER_SEC * 3.0));
		double mean = (double) total / p;
		double error = 0.0;

		for (int i = 0; i < p; i++) {
			//cerr  << resvbuf[i] << endl;
			error += pow(abs(resvbuf[i] - mean), 2);
		}
		error = (double) ( sqrt(error/p)  / mean* 100);
		fprintf(stdout, "%d\t%.4f\t%.6f\n", p, t, error);
		free(resvbuf);
	}
*/
	//fprintf(stderr, "finished\n");
	cerr << "Running Time : " << (double) (ends - start) / (CLOCKS_PER_SEC * 3.0)<< endl;
	//MPI_Finalize();

	return 1;
};

int main(int argc, char *argv[]) {
	start<StreamSummaryBuffer,DCS_FORMAT>(argc, argv);
};
